package xyz.qduwo.servlet.manager;

import xyz.qduwo.dao.UserDao;
import xyz.qduwo.entity.UserEntity;
import xyz.qduwo.util.EncryptUtils;
import xyz.qduwo.util.RespUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebServlet("/admin/manager/AddUser")
public class AddUser extends HttpServlet {
    UserEntity user = new UserEntity();
    private String msg ; //初始化返回对象

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try{
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String nickname = req.getParameter("nickname");

        user.setUsername(name);
        user.setEmail(email);
        user.setNickname(nickname);
        user.setPassword(EncryptUtils.stringToMD5(password));

        UserDao.save(user);
        msg = RespUtils.success(user); //操作成功，返回操作结果

    }catch (Exception e){
            msg = RespUtils.fail(e.toString()); //操作失败，提示错误内容
        }finally {
            resp.setContentType("application/x-json;charset=utf-8");
            resp.getWriter().print(msg); //返回操作成功信息
        }
        }
}
